package com.jjty.dataGenerator.jshjy.listener;

import com.jjty.dataGenerator.jserji.entity.ApiResponse;
import com.jjty.dataGenerator.jshjy.entity.*;
import com.jjty.dataGenerator.jshjy.event.DataInsertEvent;
import com.jjty.dataGenerator.jshjy.mapper.JsAttendanceDataMapper;
import com.jjty.dataGenerator.jshjy.mapper.JsCallDataMapper;
import com.jjty.dataGenerator.jshjy.mapper.JsHeartbeatDataMapper;
import com.jjty.dataGenerator.jshjy.mapper.JsLocationDataMapper;
import com.jjty.dataGenerator.jshjy.service.*;
import com.jjty.dataGenerator.jshjy.utils.PushHttpClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class DataInsertListener {

    @Autowired
    private PushHttpClient pushHttpClient;

    @Value("${jsedu.channel}")
    private String channel;

    @Autowired
    private JsHeartbeatDataMapper heartbeatDataMapper;

    @Autowired
    private JsLocationDataMapper locationDataMapper;

    @Autowired
    private JsCallDataMapper callDataMapper;

    @Autowired
    private JsAttendanceDataMapper attendanceDataMapper;

    @EventListener
    public void handleDataInsertEvent(DataInsertEvent event) {
        Object data = event.getData();
        if (data instanceof JsHeartbeatData) {
            pushHeartbeatData((JsHeartbeatData) data);
        } else if (data instanceof JsLocationData) {
            pushLocationData((JsLocationData) data);
        } else if (data instanceof JsCallData) {
            pushCallData((JsCallData) data);
        } else if (data instanceof JsAttendanceData) {
            pushAttendanceData((JsAttendanceData) data);
        } else if (data instanceof JsBaseData) {
            pushBaseData((JsBaseData) data);
        }
    }

    private void pushHeartbeatData(JsHeartbeatData data) {
        JsHeartbeatData request = new JsHeartbeatData();
        request.setChannel(channel);
        request.setImeiNo(data.getImeiNo());
        request.setLastHeartbeatTime(data.getLastHeartbeatTime());

        ApiResponse response = pushHttpClient.push(
                "/openapi/stu-card/sync/heartbeat",
                request
        );

        data.setPushTime(java.time.LocalDateTime.now());
        if (response.getCode() == 0) {
            data.setPushStatus(1);
            data.setPushMsg("实时推送成功");
        } else {
            data.setPushStatus(2);
            data.setPushMsg("失败原因：" + response.getMsg());
        }
        heartbeatDataMapper.updateById(data);
        log.info("数据推送结果：{}", data);
    }

    private void pushLocationData(JsLocationData data) {
        JsLocationData request = new JsLocationData();
        request.setChannel(channel);
        request.setImeiNo(data.getImeiNo());
        request.setLocationTime(data.getLocationTime());
        request.setPosition(data.getPosition());

        ApiResponse response = pushHttpClient.push(
                "/openapi/stu-card/sync/location",
                request
        );

        data.setPushTime(java.time.LocalDateTime.now());
        // 定义pushMsg最大长度（根据数据库字段实际长度调整，此处以500为例）
        int maxPushMsgLength = 500;
        String pushMsg;

        if (response.getCode() == 0) {
            data.setPushStatus(1);
            pushMsg = "实时推送成功";
        } else {
            data.setPushStatus(2);
            pushMsg = "失败原因：" + response.getMsg();
        }

        // 处理超长消息
        if (pushMsg.length() > maxPushMsgLength) {
            // 截断并添加标识
            pushMsg = pushMsg.substring(0, maxPushMsgLength) + "...[内容已截断]";
            log.warn("IMEI:{}的pushMsg超长，已截断（原始长度:{}）", data.getImeiNo(), pushMsg.length() + (pushMsg.length() - maxPushMsgLength - 13));
        }
        data.setPushMsg(pushMsg);

        locationDataMapper.updateById(data);
        log.info("数据推送结果：{}", data);
    }

    private void pushCallData(JsCallData data) {
        JsCallData request = new JsCallData();
        request.setChannel(channel);
        request.setImeiNo(data.getImeiNo());
        request.setCallTime(data.getCallTime());
        request.setPhoneNo(data.getPhoneNo());
        request.setDuration(data.getDuration());
        request.setRemainingDuration(data.getRemainingDuration());

        ApiResponse response = pushHttpClient.push(
                "/openapi/stu-card/sync/call",
                request
        );

        data.setPushTime(java.time.LocalDateTime.now());
        if (response.getCode() == 0) {
            data.setPushStatus(1);
            data.setPushMsg("实时推送成功");
        } else {
            data.setPushStatus(2);
            data.setPushMsg("失败原因：" + response.getMsg());
        }
        callDataMapper.updateById(data);
        log.info("数据推送结果：{}", data);
    }

    private void pushAttendanceData(JsAttendanceData data) {
        JsAttendanceData request = new JsAttendanceData();
        request.setChannel(channel);
        request.setImeiNo(data.getImeiNo());
        request.setRecordTime(data.getRecordTime());
        request.setType(data.getType());
        request.setState(data.getState());

        ApiResponse response = pushHttpClient.push(
                "/openapi/stu-card/sync/attendance",
                request
        );

        data.setPushTime(java.time.LocalDateTime.now());
        if (response.getCode() == 0) {
            data.setPushStatus(1);
            data.setPushMsg("实时推送成功");
        } else {
            data.setPushStatus(2);
            data.setPushMsg("失败原因：" + response.getMsg());
        }
        attendanceDataMapper.updateById(data);
        log.info("数据推送结果：{}", data);
    }

    private void pushBaseData(JsBaseData data) {
        // 处理基础数据推送逻辑
        // 这里可以根据实际需求实现
    }


}